#coding: utf-8
# GAE上不支持此脚本运行


import time
import datetime
import smtplib
import os
from email import base64mime

import settings
from django.core.management import setup_environ
setup_environ(settings) #为了在当前porject下运行，使用本项目的modoel,注册一下环境

from models import Job
from sendgroupmail import format_from_locad, format_from_gdata, Send_Group_Mail
from make_mime_type import make_MIMEMultipart


#os.sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '\\')))
#from django.conf import settings
#settings.configure()

def writeErrorLog(e):
    file = open('send_mail_error.log', 'a+')
    str = ('--> %s; on %s \n;')% (e, time.localtime())
    file.write(str)
    file.close()

def send_result_to_user(authInfo, tomail, strResult, \
                        form=u"admin@kingmailsys.com", \
                        subject=u'[定时群发结果］自动邮件，请勿回复！'):

    print("\t\t\t send_result_to_user runing...")
    mailContext = make_MIMEMultipart(form, tomail, subject, strResult.encode('utf-8'), None, None)

    smtp = smtplib.SMTP()
    try:  #测试密码是否正确
        smtp.connect(authInfo.get('server'))
        smtp.login(authInfo.get('user'), authInfo.get('password'))
        smtp.sendmail(form, tomail, mailContext.as_string())
        print "\t send result to ",tomail
    except Exception, e:
        writeErrorLog(e)
        print "\t send_result_to_user error:" , e
    smtp.quit()

    return
#end send_result_to_user()

def check_ontime_mail():
    print ("\t check ontime mail runing...")
    if Job.objects.count() == 0:
        print "\t  no jobs, return..."

    for job in Job.objects.all():
        try:
            if job.send_date <= datetime.datetime.now():
                authInfo ={}
                authInfo['server'] = job.smtp_server
                authInfo['user'] = job.login_user
                authInfo['password'] = base64mime.decode(job.login_psw)

                #处理收件列表的参数
                if job.glogin_mail and job.gpassword and job.gfile_name:

                    listMail, errorMsg = format_from_gdata(job.glogin_mail, base64mime.decode(job.gpassword),\
                                                 job.gfile_name, job.gwksht_name)
                else:

                    listMail, errorMsg = format_from_locad(job.mail_list)

                #job.user_id
                if listMail == None: #发送一个失败信息给用户
                    send_result_to_user(authInfo, job.sender_mail, u'Send E-Mail on time is failure! Plase check your Receiver format and send again!\n' +\
                                        ("mail subject : %s \n Context: %" % (job.subject, job.mail_context)))
                else:
                    print listMail
                    rtMsg, mailBoby = Send_Group_Mail(authInfo, job.sender_mail, listMail, job.main_index,\
                                                   job.marco, job.subject, job.mail_context, \
                                                   job.attach_file_path, job.send_myself)
                    print "\t Send_Group_Mailing.... and delete record...."
                    send_result_to_user(authInfo, job.sender_mail, rtMsg + mailBoby)

                job.delete()
        except Exception, e:
            print "database error...", e
            job.delete()
            writeErrorLog(e)

    return None
#end send_mail()



def loop_ontime_send_mails():
    while 1:
        print "loop....."
        try:
            check_ontime_mail()
        except Exception, e:
            print "loop_ontime_send_mails error: " , e
            writeErrorLog(e)
        time.sleep(10) #每10秒检查一次
    pass

if __name__ == '__main__':
    print "go....."
    loop_ontime_send_mails()
    writeErrorLog('Ontimesendmail.py is exited on %s \n;')

